package foliotracker;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * Default implementation of IPortfolioRepository using Java serialisation to serialise portfolios to a file.
 */
public class PortfolioRepository implements IPortfolioRepository
{
	/*
	 * use an ObjectOutputStream/ObjectInputStream to save and load respectively.
	 */

	@Override
	public PortfolioCollection load(String path) throws SaveLoadException
	{
		try 
		{
			FileInputStream fis = new FileInputStream(path);
			ObjectInputStream in = new ObjectInputStream(fis);
			
			PortfolioCollection collection = (PortfolioCollection)in.readObject();
			in.close();
			
			return collection;
	    }
		catch (IOException ex)
		{
			throw new SaveLoadException("There was a problem opening the file: " + ex.getMessage());
		}
		catch (ClassNotFoundException ex)
		{
			throw new SaveLoadException("The file was in an invalid format.");
		}
	}
	
	@Override
	public void save(String path, PortfolioCollection collection) throws SaveLoadException
	{
		try 
		{
			FileOutputStream fos = new FileOutputStream(path);
			ObjectOutputStream out = new ObjectOutputStream(fos);
	        out.writeObject(collection);
	        out.flush();
	        out.close();
		}
		catch (IOException ex)
		{
			throw new SaveLoadException("There was a problem opening the file: " + ex.getMessage());
		}
	}
}

